package com.ruoyi.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.pojo.dto.QuestionDto;
import com.ruoyi.pojo.dto.SearchQuestionDto;
import com.ruoyi.pojo.vo.QuestionVo;
import com.ruoyi.service.IUnreadCountService;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.mapper.QuestionMapper;
import com.ruoyi.domain.Question;
import com.ruoyi.service.IQuestionService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户反馈Service业务层处理
 *
 * @author qyb
 * @date 2023-12-26
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Service
public class QuestionServiceImpl implements IQuestionService {

    private final Long ADMIN = 1l;//管理员账户uuid关联未读消息表

    private final Long ADMIN_ROLE = 1l;//管理员角色
    private final Long TEACHER_ROLE = 3l;//老师角色

    private final QuestionMapper questionMapper;
    private final IUnreadCountService unreadCountService;
    private final SysUserRoleMapper sysUserRoleMapper;
    private final SysUserMapper sysUserMapper;


    @Override
    public TableDataInfo getList(SearchQuestionDto questionDto) {

        List<Question> questionList;
        if (!isAdmin(SecurityUtils.getUserId())){
            questionDto.setUserId(SecurityUtils.getUserId());
            PageHelper.startPage(questionDto.getPageNum(),questionDto.getPageSize());
            questionList=questionMapper.getListByUserIdNew(questionDto);
        }else {
            PageHelper.startPage(questionDto.getPageNum(),questionDto.getPageSize());
//            questionList= questionMapper.getList(questionDto);
            questionList= questionMapper.getListNew(questionDto);
        }
        List<QuestionVo> questionVos = copyVoList(questionList);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(questionVos);
        rspData.setTotal(new PageInfo(questionList).getTotal());
        return rspData;

    }

    private List<QuestionVo> copyVoList(List<Question> questionList) {
        List<QuestionVo> questionVos=new ArrayList<>();
        for (Question question : questionList) {
            QuestionVo questionVo=new QuestionVo();
            BeanUtils.copyProperties(question,questionVo);
            SysUser sysUser = sysUserMapper.selectUserById(question.getUserId());
            questionVo.setName(sysUser.getUserName());
            questionVos.add(questionVo);
        }
        return questionVos;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult addQuestion(QuestionDto questionDto) {
        Question question = new Question();
        Long userId=questionDto.getUserId()!=null?questionDto.getUserId():SecurityUtils.getUserId();
//        String userName=questionDto.getName()!=null?questionDto.getName():SecurityUtils.getUsername();
        BeanUtils.copyProperties(questionDto, question);
        question.setCreateTime(DateUtils.getNowDate());
        question.setCreateBy(String.valueOf(userId));
        //判断是否是系统消息，系统消息管理员默认已读

        question.setIsAdminTrue(1);
        question.setIsUserTrue(questionDto.getIsUserTrue());
        question.setIsSolve(1);
//        question.setName(userName);
        //用户发送的消息却未读，说明是系统消息
        if (question.getIsUserTrue()!=null&&question.getIsUserTrue()==1){
            unreadCountService.addCount(userId,1);
            //标记系统消息
            question.setRemark("2");
            question.setIsAdminTrue(0);
        }else {
            //添加管理员未读消息数
            unreadCountService.addCount(SecurityUtils.getUserId(), 2);
        }

        if (questionMapper.insertQuestion(question) == 1) {
            return AjaxResult.success("问题反馈成功");
        } else {
            return AjaxResult.error("问题反馈成功失败");
        }

    }

    @Override
    public AjaxResult deleteQuestion(Long uuid) {

        Question question = questionMapper.selectQuestionByUuid(uuid);
        if (question == null) {
            return AjaxResult.error(515, "未找到删除记录");
        }
        if (!isAdmin(SecurityUtils.getUserId()) && question.getUserId() != SecurityUtils.getUserId()) {
            return AjaxResult.error(510, "无权限删除");
        }
        question.setIsDelete(1);
        //删除未读消息数量
        if (question.getIsUserTrue() == 1) {
            unreadCountService.clearCount(question.getUserId(), 1);
        }
        if (question.getIsAdminTrue() == 1) {
            unreadCountService.clearCount(ADMIN, 2);
        }
        return questionMapper.updateQuestion(question) == 1 ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult clearMessage(Long uuid) {

        if (clearMessage(uuid, SecurityUtils.getUserId())) {
            return AjaxResult.success("已读消息");
        }
        return AjaxResult.error("更新失败");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult backMessage(QuestionDto questionDto) {
        Question question = new Question();
        BeanUtils.copyProperties(questionDto, question);
        question.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
        question.setUpdateTime(DateUtils.getNowDate());
        question.setIsUserTrue(1);
        question.setIsAdminTrue(0);
        //用户未读消息数+1 管理员消息数不用减，在获取反馈详情的时候减
        unreadCountService.addCount(question.getUserId(), 1);
        //管理员未读消息减一
        unreadCountService.clearCount(ADMIN,2);
        question.setIsSolve(0);
        return questionMapper.updateQuestion(question) == 1 ? AjaxResult.success("回复成功") : AjaxResult.error("回复失败");

    }

    @Override
    public AjaxResult getQuestionInfo(Long uuid, Integer type, Long userId) {
        QuestionVo questionVo = new QuestionVo();
        Question question = questionMapper.selectQuestionByUuid(uuid);
        if (type == 1) {
            if (question.getIsUserTrue() == 1) {
                //用户已读
                unreadCountService.clearCount(userId, 1);
            }
            question.setIsUserTrue(0);
            BeanUtils.copyProperties(question, questionVo);
            questionVo.setIsUserTrue(1);
        }

        if (type == 2) {
            if (question.getIsAdminTrue() == 1) {
                //管理员已读
                unreadCountService.clearCount(ADMIN, 2);
            }
            question.setIsAdminTrue(0);
            BeanUtils.copyProperties(question, questionVo);
            questionVo.setIsAdminTrue(0);
        }
        //更新反馈消息
        questionMapper.updateQuestion(question);

        return AjaxResult.success(questionVo);
    }

    @Override
    public AjaxResult clearAllMessage(Long userId) {

        if (clearAllMessages(userId)) {
            return AjaxResult.success("清除成功");
        }
        return AjaxResult.error("清除失败");
    }

    /**
     * 单条消息已读
     *
     * @param uuid
     * @param userId
     * @return
     */
    public boolean clearMessage(Long uuid, Long userId) {
        Question question = questionMapper.selectQuestionByUuid(uuid);
        if (question == null) {
            return false;
        }
        if (!isAdmin(userId)) {
            //更新用户阅读消息
            question.setIsUserTrue(0);
            unreadCountService.clearCount(question.getUserId(), 1);

        } else {
            question.setIsAdminTrue(0);
            unreadCountService.clearCount(ADMIN, 2);
        }
        return questionMapper.updateQuestion(question) == 1;
    }

    /**
     * 清除未读消息
     *
     * @param userId
     * @return
     */
    public boolean clearAllMessages(Long userId) {
        if (!isAdmin(userId)) {
            //更新用户阅读消息
            unreadCountService.clearAllCount(userId);
            return questionMapper.updateUserRead()==1;

        } else {
            //更新管理员阅读消息
            unreadCountService.clearAllCount(ADMIN);
            return questionMapper.updateAdminRead() == 1;
        }

    }

    private boolean isAdmin(Long userId) {
        SysUserRole roleByUserId = sysUserRoleMapper.getRoleByUserId(userId);
        if (roleByUserId==null){
            return false;
        }
        if (roleByUserId.getRoleId() == ADMIN_ROLE||roleByUserId.getRoleId()==TEACHER_ROLE) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 查询用户反馈列表
     *
     * @param question 用户反馈
     * @return 用户反馈
     */
    @Override
    public List<Question> selectQuestionList(Question question) {
        return questionMapper.selectQuestionList(question);
    }


}
